<template>
  <div class="team-schedulechecker">
    <!-- 顶部日期查询导航 -->
    <div class="thc-title" @click="showTimerChoosePicker">
      <image
        src="https://ustatic.joymew.com/%20joymewApp/img/my/team/calendar.png"
        mode="aspectFit"
      />
      <span class="th-date-text">
        {{ formattedDate }} {{ selectedTimeInterval }}
      </span>
      <span>以下成员有空挡：</span>
    </div>
    <!-- 有空闲档期的成员列表 -->
    <div class="th-c-body">
      <div
        v-for="(member, index) in availableMembers"
        :key="index"
        class="th-cb-item"
      >
        <image :src="member.avatar" mode="aspectFit" class="th-cb-avatar-img" />
        <span class="th-cb-name"> 主持人 {{ truncateName(member.name) }} </span>
        <span class="th-cb-price">{{ member.price }}元</span>
        <image
          @click="handleCall(member.telephone)"
          src="https://ustatic.joymew.com/%20joymewApp/img/my/team/phone.png"
          class="th-cb-phone-img"
          mode="aspectFit"
        />
      </div>
    </div>
    <!-- 时间段选择器 -->
    <TimeRangePicker
      :show="pickerShow"
      :columns="pickerColumns"
      @close="pickerShow = false"
      closeOnClickOverlay
      @cancel="pickerShow = false"
      :defaultIndex="defaultIndex"
      @confirm="handlePickerConfirm"
    />
  </div>
</template>

<script lang="ts" setup>
import TimeRangePicker from "@/components/TimeRangePicker.vue";
import { getTeamMemberNotSchedule } from "@/api/hlr-api";

const today = new Date();
const TIME_INTERVALS = ["早上", "上午", "午宴", "下午", "晚宴", "全天"];
const availableMembers = ref([]);
// 控制时间段选择器显隐
const pickerShow = ref(false);
const selectedDate = ref({
  year: today.getFullYear(),
  month: today.getMonth() + 1,
  day: today.getDate(),
  interval: "午宴",
});
const pickerColumns = computed(() => {
  const currentYear = new Date().getFullYear();
  return [
    Array.from({ length: currentYear - 2020 }, (_, i) => `${2021 + i}年`),
    Array.from({ length: 12 }, (_, i) => `${i + 1}月`),
    Array.from(
      { length: 31 },
      (_, i) => `${(i + 1).toString().padStart(2, "0")}日`
    ),
    TIME_INTERVALS,
  ];
});
const defaultIndex = computed(() => {
  return [
    today.getFullYear() - 2021,
    today.getMonth(),
    today.getDate() - 1,
    2, // 默认选中"午宴"
  ];
});

const props = defineProps<{
  teamId: string | number;
}>();

// 选中时间段的日期和时间段
const formattedDate = computed(() => {
  const { year, month, day } = selectedDate.value;
  return `${year}年${month}月${day}日`;
});
const selectedTimeInterval = computed(() => {
  return selectedDate.value.interval;
});

const handleCall = (phone: string) => {
   uni.makePhoneCall({ phoneNumber: phone });
};

const truncateName = (name: string) => {
  return name;
};

const handlePickerConfirm = async ({ value } = {} as any) => {
  const [year, month, day, interval] = value;
  selectedDate.value = {
    year: parseInt(year),
    month: parseInt(month),
    day: parseInt(day),
    interval,
  };
  // 请求档期空闲的成员列表
  availableMembers.value = await loadAvailableMembers();
  pickerShow.value = false;
};

const showTimerChoosePicker = () => {
  pickerShow.value = true;
};

/**
 * 格式化日期为 YYYY-MM-DD
 * @param {Date} date - 日期对象
 * @returns {string}
 */
function formatDateForAPI(date: any) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

const loadAvailableMembers = async () => {
  const date = selectedDate.value;
  const res = await getTeamMemberNotSchedule({
    team_id: props.teamId,
    query_date_val: formatDateForAPI(
      new Date(date.year, date.month - 1, date.day)
    ),
    time_interval: selectedDate.value.interval,
  });
  if(!res) {
    return [];
  }

  return (
    res.data.list?.map((item) => ({
      telephone: item.phonenumber || "",
      avatar: item.user_headimg || "",
      price: item.total_price || 0,
      name: item.user_qm_name || "",
    })) || []
  );
};

// 监听 teamId 变化，当有值时立即调用 loadAvailableMembers
watch(
  () => props.teamId,
  async (newTeamId) => {
    if (newTeamId) {
      availableMembers.value = await loadAvailableMembers();
    }
  },
  { immediate: true }
);
</script>

<style scoped>
/* 顶部日期查询导航 */
.thc-title {
  display: flex;
  align-items: center;
  height: 92rpx;
  margin: 16rpx 0;
  background-color: #fff;
}
.thc-title image {
  width: 40rpx;
  height: 40rpx;
  margin-left: 20rpx;
}
.thc-title .th-date-text {
  margin-left: 8rpx;
  font-weight: 500;
  color: #ff7499;
}
.thc-title span:last-child {
  margin-left: 16rpx;
  font-weight: 400;
}
.th-c-body {
  background-color: #fff;
}
.th-c-body .th-cb-item {
  display: flex;
  align-items: center;
  height: 96rpx;
  margin: 0 20rpx;
  border-bottom: 1rpx solid #f3f3f3;
}
.th-c-body .th-cb-item .th-cb-avatar-img {
  width: 64rpx;
  height: 64rpx;
  margin-right: 20rpx;
  border-radius: 50%;
}
.th-c-body .th-cb-item .th-cb-price {
  margin-left: auto;
}
.th-c-body .th-cb-item .th-cb-phone-img {
  width: 48rpx;
  height: 48rpx;
  margin-left: 48rpx;
}
</style>
